package com.reggie.category.controller;

import com.reggie.category.entity.Category;
import com.reggie.category.service.CategoryService;
import com.reggie.configuration.common.Result;
import com.reggie.configuration.common.tableList;
import com.reggie.configuration.myException.RepetitionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<tableList> selectByCondition(Integer page, Integer pageSize) {
        return categoryService.selectByCondition(page, pageSize);
    }

    /**
     * 添加新的分类，抛出的异常为分类的名称出现重复
     *
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> InsertCategory(@RequestBody Category category) {
        log.info("新分类的信息{}", category);

        int i = categoryService.selectByName(category.getName());
        if (i > 0) {
            throw new RepetitionException(category.getName());
        }
        categoryService.save(category);
        return Result.success("添加成功");
    }

    /**
     * 修改分类及套餐
     *
     * @param category
     * @return
     */
    @PutMapping
    public Result<String> updateCategory(@RequestBody Category category) {
        categoryService.updateById(category);
        return Result.success("修改成功");
    }

    /**
     * 删除分类，当然实在没有绑定菜品的前提下
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public Result<String> removeCategory(String id) {
        final Long aLong = Long.valueOf(id);
        return categoryService.selectByID(aLong);
    }

    /**
     * 用于在新增菜品的时候展示菜品的分类列表
     *
     * @return
     */
    @GetMapping("list")
    public Result<List<Category>> selectByType() {
        return categoryService.selectByType();
    }


}
